package com.calligraphy.order.interceptor;

import com.calligraphy.bases.utils.JwtUtil;
import com.calligraphy.user.common.UserOutput;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author hy
 * @Date 2019/1/24 11:11
 **/
public class LoginInterceptor extends HandlerInterceptorAdapter {

    /**
     * 定义一个线程域，存放登录用户
     */
    private static final ThreadLocal<UserOutput> t1 = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        try{
            Map<String, String> map = null;
            map = JwtUtil.verifyToken(token);
            String email =  map.get("email");
            UserOutput userOutput = new UserOutput();
            userOutput.setEmail(email);
            //放入线程域
            t1.set(userOutput);
            return true;
        }catch (Exception e){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
    }

    public static UserOutput getLoginUser(){
        return t1.get();
    }
}
